#include "ItemDelegate.h"
#include <Item.h>
#include <QComboBox>



ItemDelegate::ItemDelegate(QObject *parent) :
    QStyledItemDelegate(parent)
{
}



QWidget* ItemDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    if (!index.isValid()) return QStyledItemDelegate::createEditor(parent, option, index);

    QObject* obj = static_cast<QObject*>(index.internalPointer());
    AbstractItem* item = dynamic_cast<AbstractItem*>(obj);
    if (!item) return QStyledItemDelegate::createEditor(parent, option, index);

    if(item->category() != ItemCategory_Reference) return QStyledItemDelegate::createEditor(parent, option, index);

    if (index.column() != Item::ValueData) return QStyledItemDelegate::createEditor(parent, option, index);

    QComboBox* combo = new QComboBox(parent);
    return combo;
}



void ItemDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    if (!index.isValid()) return;

    QComboBox* combo = dynamic_cast<QComboBox*>(editor);
    if (!combo) return;

    QObject* obj = static_cast<QObject*>(index.internalPointer());
    AbstractItem* item = dynamic_cast<AbstractItem*>(obj);

    if (item->category() != ItemCategory_Reference) return;

    QList<Item*> options = item->rootItem()->findChildren<Item*>();
    foreach (Item* option, options)
    {
        if (!option || option->category() != ItemCategory_Item) continue;

        combo->addItem(option->name(), option->objectName());
        //combo->addItem(QString("%1 (%2)").arg(option->name()).arg(option->objectName()), option->objectName());
    }


}



void ItemDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
    if (!index.isValid()) return;

    QComboBox* combo = dynamic_cast<QComboBox*>(editor);
    if (!combo) return;

    model->setData(index, combo->itemData(combo->currentIndex()));

}
